<template>
  <div id="geetest_captcha"></div>
</template>

<script setup>
import { ref } from 'vue'
import api from '@/http/index'
import { ElMessage } from 'element-plus'
const CaptchaInstance = ref()
let validateResolve = null
let validateReject = null

const captchaHandler = (captchaObj) => {
  CaptchaInstance.value = captchaObj
  captchaObj
    .appendTo('#captcha')
    .onReady(function () {})
    .onNextReady(function () {})
    .onBoxShow(function () {})
    .onError(function (e) {
      validateReject(false, e)
    })
    .onSuccess(async () => {
      const result = CaptchaInstance.value.getValidate()
      const validResult = await api.auth.geetest(result)
      const valid = validResult.data.valid
      if (valid) {
        validateResolve(true)
      }
      validateReject(false, validResult.msg)
    })
}

window.initGeetest4(
  {
    captchaId: '3d5a0e662b8d500ea57befebd6a5d77d',
    product: 'bind',
  },
  captchaHandler,
)

const validate = () => {
  if (CaptchaInstance.value) {
    CaptchaInstance.value.showCaptcha()
  } else {
    ElMessage.warning('请等待验证码初始化完成，稍后再试')
  }
  return new Promise((resolve, reject) => {
    validateResolve = resolve
    validateReject = reject
  })
}

defineExpose({
  validate,
})
</script>

<style lang="scss" scoped></style>
